"use strict"

var fs = require('fs')

exports.storeMove = function(payload) {
	var folder = "stored-moves/",
		move = JSON.parse(payload),
		gameId = move.gameId
	
	fs.writeFileSync(
		folder + gameId + ".txt",				//location on the fs
		payload,								//json blob to store (should already be encoded)
		'utf8'									//encoding
	)
	
	return true
}

exports.retrieveMove = function(payload) {
	var folder = "stored-moves/",
		move = JSON.parse(payload),
		gameId = move.gameId
	
	try {
		var data = fs.readFileSync(
			folder + gameId + ".txt",			//location on the fs
			'utf8'								//encoding
		)
	} catch(e) {
		//don't need to process this error, just do nothing
	}
	
	return ( data ? data : false )				//return 'false' if no data retrieved
}

exports.storeGame = function(payload) {
	var folder = "stored-games/",
		move = JSON.parse(payload),
		gameId = move.gameId
	
	fs.writeFileSync(
		folder + gameId + ".txt",				//location on the fs
		payload,								//json blob to store (should already be encoded)
		'utf8'									//encoding
	)
	
	return true
}

exports.retrieveGame = function(payload) {
	var folder = "stored-games/",
		move = JSON.parse(payload),
		gameId = move.gameId
	
	var data = fs.readFileSync(
		folder + gameId + ".txt",				//location on the fs
		'utf8'									//encoding
	)
	
	return ( data ? data : false )				//return 'false' if no data retrieved
}

exports.gamesList = function() {
	var folder = "stored-games/",
		files = fs.readdirSync(folder),							//create list of games
		gamesList = [ ]
	
	var data, json
	for (var i=0, ii=files.length; i<ii; i++) {
		data = fs.readFileSync(folder + files[i], 'utf8')
		json = JSON.parse(data)									//load each game and parse to json
		if (json.players.length < 2) {
			gamesList.push(json)								//add only games which have 1 (or 0) players
		}
	}
	
	return { games: gamesList }									//return games list in correct format
}